﻿/**
 * Created by ShaoboZhu on 2017/8/29.
 */
(function($){
    var tableTemplate  = "",settings = {},
        _setting = {
            head : [],
            rowData : [],
            zColumns : [],
            sort : true,
            showSerialId : true,
            usePager : true,
            tableAlign : "center",
            fixedHead : true,
            pageInfo :{pageSize:10,pageNum:1,totalPage: 1,totalRecords:0},
            pageSizeArr : [10,20,50,100,200,500],
            async : false,
            requestParam: {
                type: "get",
                dataType: "json",
                url: "",
                otherParam: []
            },
            operation : [],
            trClickCb : null,
            callback : {
                asyncSuccess : null,
                asyncError : null,
                afterGenerateTable : null
            }
        },
        _init = {
            template : function () {
                $.ajax({
                    url:"/static/js/lib/zTable/zTableTemp.html",
                    dataType:"html",
                    async:false,
                    complete: function (data) {
                        tableTemplate = data.responseText;
                    }
                });
            }
        },
        _event = {
            bingEvent : function (setting) {
                $(setting.tableObj).unbind("click").bind("click",function (e) {
                    e.stopPropagation();
                    if($(e.target).hasClass("zTable-pageBefore")){
                        if(_handle.pageBefore(setting)){data.getColumnData(setting);}
                    }
                    if($(e.target).hasClass("zTable-pageNext")){
                        if(_handle.pageNext(setting)){data.getColumnData(setting);};
                    }
                    if($(e.target).hasClass("zTable-page-block")){
                        setting.pageInfo.pageNum = Number($(e.target).html());
                        data.getColumnData(setting);
                    }
                    if($(e.target).hasClass("zTable-page-jump-btn")) {
                        var pageNum = $(setting.tableObj).find(".zTable-page-jump-num").val();
                        if(pageNum!=""){
                            setting.pageInfo.pageNum = Number(pageNum);
                            data.getColumnData(setting);
                        }
                    }
                    for(var i=0;i<setting.operation.length;i++){
                        var op = setting.operation[i];
                        if($(e.target).hasClass(op.className)){
                            if((typeof op.callback) == "function"){
                                op.callback($(e.target).parents("tr"));
                            }
                        }
                    }
                    if(e.target.tagName == "TH"&&!$(e.target).hasClass("serial-id")&&!$(e.target).hasClass("zTable-operation-th")) {
                        _handle.thClickHandle($(e.target),setting);
                    }
                    if(e.target.tagName == "TD"&&$(e.target).parent().hasClass("zTable-body-tr")) {
                        if((typeof setting.trClickCb) == "function"){
                            setting.trClickCb($(e.target).parents("tr"));
                        }
                    }
                });
                $(setting.tableObj).find(".zTable-page-size").change(function () {
                    setting.pageInfo.pageNum = 1;
                    setting.pageInfo.pageSize = Number($(this).val());
                    data.getColumnData(setting);
                })
            }
        },
        _handle = {
            pageBefore : function (setting) {
                var pageNum = setting.pageInfo.pageNum;
                if(pageNum>1){
                    setting.pageInfo.pageNum = pageNum - 1;
                    return true;
                }else{
                    return false;
                }
            },
            pageNext : function (setting) {
                var pageNum = setting.pageInfo.pageNum,
                    totalPage = setting.pageInfo.totalPage;
                if(pageNum!=totalPage){
                    setting.pageInfo.pageNum = pageNum + 1;
                    return true;
                }else{
                    return false;
                }
            },
            thClickHandle : function ($th,setting) {
                var sortType = $th.attr("sorttype");
                $th.siblings().removeAttr("sorttype");
                if(sortType == "asc"){
                    sortType = "desc";
                    $th.attr("sorttype","desc");
                }else{
                    sortType = "asc";
                    $th.attr("sorttype","asc");
                }
                view.sort($th.index(),sortType,setting);
            }
        },
        tools = {
            clone: function (obj){
                if (obj === null) return null;
                var o = tools.isArray(obj) ? [] : {};
                for(var i in obj){
                    o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? tools.clone(obj[i]) : obj[i]);
                }
                return o;
            },
            isArray: function(arr) {
                return Object.prototype.toString.apply(arr) === "[object Array]";
            },
            isEmpty: function (){
                var len = arguments.length;
                for(var i=0;i<len;i++){
                    var a = arguments[i];
                    if($.isPlainObject(a)){
                        if($.isEmptyObject(a)){
                            return true;
                        }
                    }else if($.isArray(a)){
                        if(a.length==0){
                            return true;
                        }
                    }else{
                        if(a==null|| a==undefined || $.trim(a)==""){
                            return true;
                        }
                    }
                }
                return false;
            },
            decodeRecord:function(num){
                var num1=0,num2=0,num3= 0;
                var array1 = num.split('亿'),array2 = [];
                if(array1.length>1){
                    num1 = parseInt(array1[0]);
                    array2 = array1[1].split('万');
                }else{
                    num1 = 0;
                    array2 = array1[0].split('万');
                }
                if(array2.length>1){
                    num2 = parseInt(array2[0]);
                    num3 = parseInt(array2[1]);
                }else{
                    num2 = 0;
                    num3 = parseInt(array2[0]);
                }
                return [num1,num2,num3];
            },
            template : function (text, data) {
                var render;
                var noMatch = /(.)^/;
                var escapes = {
                    "'" : "'",
                    '\\' : '\\',
                    '\r' : 'r',
                    '\n' : 'n',
                    '\t' : 't',
                    '\u2028' : 'u2028',
                    '\u2029' : 'u2029'
                };
                var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
                var settings = {
                    evaluate : /<@([\s\S]+?)@>/g,
                    interpolate : /<@=([\s\S]+?)@>/g,
                    escape : /<@-([\s\S]+?)@>/g
                };
                var matcher = new RegExp([(settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source].join('|') + '|$', 'g');

                var index = 0;
                var source = "__p+='";
                text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
                    source += text.slice(index, offset).replace(escaper, function(match) {
                        return '\\' + escapes[match];
                    });
                    if(escape) {
                        source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
                    }
                    if(interpolate) {
                        source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
                    }
                    if(evaluate) {
                        source += "';\n" + evaluate + "\n__p+='";
                    }
                    index = offset + match.length;
                    return match;
                });
                source += "';\n";
                if(!settings.variable)
                    source = 'with(obj||{}){\n' + source + '}\n';
                source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + "return __p;\n";
                try {
                    render = new Function(settings.variable || 'obj', source);
                } catch (e) {
                    e.source = source;
                    throw e;
                }
                if(data)
                    return render(data);
                var template = function(data) {
                    return render.call(this, data);
                };
                template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
                return template;
            }
        },
        data = {
            getColumnData : function (setting) {
                var rp = setting.requestParam;
                if(rp.url&&rp.url!=""){
                    $.ajax({
                        cache: false,
                        type: rp.type,
                        url: rp.url,
                        data: $.extend({},rp.otherParam,{page:setting.pageInfo.pageNum}),
                        dataType: setting.async.dataType,
                        success: function (msg) {
                            if ((typeof setting.callback.asyncSuccess) == "function") {
                                var tempData = setting.callback.asyncSuccess(msg);
                                $.extend(setting, tempData);
                                view.generateTable(setting)
                            }
                        }
                    })
                }
            },
            getSetting: function(treeId) {
                return settings[treeId];
            }
        },
        view = {
            generateTable : function (setting) {
                $(setting.tableObj).html(tools.template(tableTemplate,{setting:setting}));
                _event.bingEvent(setting);
                $(setting.tableObj).find(".zTable-right-line").css("left",$(setting.tableObj).find(".zTable-table").width()-1);
                if(setting.fixedHead){
                    view.createFixedHead(setting);
                }
                if(setting.sort){
                    $(setting.tableObj).find(".zTable").addClass("zTable-sort");
                }
                if((typeof setting.callback.afterGenerateTable) == "function"){
                    setting.callback.afterGenerateTable(setting.tableObj);
                }
            },
            createFixedHead : function (setting) {
                var $fixedHead = $("<div class='zTable-fixed-head'><table class='fixed-head-table'></table></div>"),
                    $zTable = $(setting.tableObj).find(".zTable");
                $zTable.append($fixedHead);
                $fixedHead.css({width:$zTable.find("table").width()});
                $fixedHead.find(".fixed-head-table").html($zTable.find("thead").clone());
                $fixedHead.find("tr th").each(function (i,v) {
                    $(v).width($zTable.find("table>thead>tr>th").eq(i).width()+1);
                })
                $zTable.scroll(function () {
                    $fixedHead.css("top",$(this).scrollTop());
                })
            },
            ClearState : function (viewState,dom_Table) {
                for (var x = 0; x < dom_Table.rows[0].cells.length; x++) {
                    viewState[x] = 0;
                }
            },
            sort : function (colIndex,type,setting) {
                var dom_Table = $(setting.tableObj).find(".zTable-table")[0];
                var viewState = [];
                if(type == "asc" && viewState[colIndex] == 1){
                    return;
                }
                if(type == "desc" && viewState[colIndex] == 2){
                    return;
                }
                //初始化所有列为未点击状态
                $(dom_Table).find("thead th").each(function(){
                    $(this).children("i").removeClass("fa-long-arrow-up");
                    $(this).children("i").removeClass("fa-long-arrow-down");
                });
                $(dom_Table).parents(".fixed-table").find(" .fixed-table-head div").each(function(){
                    $(this).children("i").removeClass("fa-long-arrow-up");
                    $(this).children("i").removeClass("fa-long-arrow-down");
                });
                var isEqual=true;
                var Sorter = [], isNumber = true;
                for (var x = 1; x < dom_Table.rows.length; x++) {
                    Sorter[x - 1] = [dom_Table.rows[x].cells[colIndex].innerHTML, x];
                    if(isNumber) {
                        isNumber = $.isNumeric(Sorter[x - 1][0]);
                    }
                }
                Sorter,isEqual = view.sortFunction(isNumber,Sorter,isEqual);
                if (viewState[colIndex]) {//已排序
                    if (viewState[colIndex] == 1 && !isEqual) {
                        Sorter.reverse();
                    }
                }else{
                    if(type == "desc" && !isEqual){
                        Sorter.reverse();
                    }
                }
                var Rank = [];
                for (var x = 0; x < Sorter.length; x++) {
                    Rank[x] = dom_Table.rows[Sorter[x][1]].outerHTML;
                }
                for (var x = 1; x < dom_Table.rows.length; x++) {
                    dom_Table.rows[x].outerHTML = Rank[x-1];
                }
                if (viewState[colIndex]) {//已排序
                    if (viewState[colIndex] == 1) {
                        view.ClearState(viewState,dom_Table);
                        viewState[colIndex] = 2;
                        $(dom_Table).find("thead th:eq(" + colIndex + ")").children("i").removeClass("fa-long-arrow-up");
                        $(dom_Table).find("thead th:eq(" + colIndex + ")").children("i").addClass("fa-long-arrow-down");
                        $(dom_Table).parents(".fixed-table").find(" .fixed-table-head > div:eq(" + colIndex + ")").children("i").removeClass("fa-long-arrow-up");
                        $(dom_Table).parents(".fixed-table").find(" .fixed-table-head > div:eq(" + colIndex + ")").children("i").addClass("fa-long-arrow-down");
                    } else {
                        view.ClearState(viewState,dom_Table);
                        viewState[colIndex] = 1;
                        $(dom_Table).find("thead th:eq(" + col + ")").children("i").removeClass("fa-long-arrow-down");
                        $(dom_Table).find("thead th:eq(" + col + ")").children("i").addClass("fa-long-arrow-up");
                        $(dom_Table).parents(".fixed-table").find(" .fixed-table-head > div:eq(" + colIndex + ")").children("i").removeClass("fa-long-arrow-down");
                        $(dom_Table).parents(".fixed-table").find(" .fixed-table-head > div:eq(" + colIndex + ")").children("i").addClass("fa-long-arrow-up");
                    }
                } else {//未排序
                    view.ClearState(viewState,dom_Table);
                    if(type == "desc"){
                        viewState[colIndex] = 2;
                        $(dom_Table).find("thead th:eq(" + colIndex + ")").children("i").addClass("fa-long-arrow-down");
                        $(dom_Table).parents(".fixed-table").find(" .fixed-table-head > div:eq(" + colIndex + ")").children("i").addClass("fa-long-arrow-down");
                    }else{
                        viewState[colIndex] = 1;
                        $(dom_Table).find("thead th:eq(" + colIndex + ")").children("i").addClass("fa-long-arrow-up");
                        $(dom_Table).parents(".fixed-table").find(" .fixed-table-head > div:eq(" + colIndex + ")").children("i").addClass("fa-long-arrow-up");
                    }
                }
            },
            sortFunction : function(isNumber,Sorter,isEqual){
                if(isNumber){
                    for (var x = 0; x < Sorter.length; x++) {
                        for (var y = x + 1; y < Sorter.length; y++) {
                            if(isEqual && parseFloat(Sorter[y][0]) != parseFloat(Sorter[x][0])){
                                isEqual = false;
                            }
                            if (parseFloat(Sorter[y][0]) < parseFloat(Sorter[x][0])) {
                                var tmp = Sorter[x];
                                Sorter[x] = Sorter[y];
                                Sorter[y] = tmp;
                            }
                        }
                    }
                }else{
                    for (var x = 0; x < Sorter.length; x++) {
                        for (var y = x + 1; y < Sorter.length; y++) {
                            if(isEqual && Sorter[x][0].localeCompare(Sorter[y][0]) != 0){
                                isEqual = false;
                            }
                            if (Sorter[x][0].localeCompare(Sorter[y][0]) == 1) {
                                var tmp = Sorter[x];
                                Sorter[x] = Sorter[y];
                                Sorter[y] = tmp;
                            }
                        }
                    }
                }
                return Sorter,isEqual;
            }
        };
    _init.template();
    $.fn.zTable = {
        init : function (obj, zSetting, zColumns) {
            var setting = tools.clone(_setting);
            $.extend(true, setting, zSetting,{zColumns:zColumns ? zColumns:[]});
            setting.tableId = obj.attr("id");
            setting.tableObj = obj;
            setting.tableObj.empty();
            settings[setting.tableId] = setting;
            if(setting.async){
                data.getColumnData(setting);
            }else {
                view.generateTable(setting);
            }
        },
        refresh : function (id) {
            var s = data.getSetting(id);
            if(s.async){
                data.getColumnData(s);
            }else {
                view.generateTable(s);
            }
        }
    }
})(jQuery);
function isEmpty(){
    var len = arguments.length;
    if(len==0){ return true; }
    for(var i=0;i<len;i++){
        var a = arguments[i];
        if(typeof a === "undefined" || a == null || (typeof a === "string" && a.trim() == "")){
            return true;
        }else if(typeof a === "object"){
            var flg = true;
            for (var k in a ) {
                flg=false;
                break;
            }
            if(flg){ return true; }
        }
    }
    return false;
}
/**
 * 扩展DATE属性，增加日期格式化方法
 * @param f
 * @returns {*}
 */
Date.prototype.zTableFormat = function(f){
    var o ={
        "M+" : this.getMonth()+1, //month
        "d+" : this.getDate(),    //day
        "H+" : this.getHours(),   //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
        "S" : this.getMilliseconds() //millisecond
    };
    if(/(y+)/.test(f))f=f.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(f))f = f.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));return f
};
